package org.example.util;

import org.example.constant.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;

public class JavaHttpRequest {

    private static final Logger log = LoggerFactory.getLogger(JavaHttpRequest.class);

    private static SSLSocketFactory socketFactory;

    static {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }};
        try {
            SSLContext sc = SSLContext.getInstance("TLS", "SunJSSE");
            sc.init(null, trustAllCerts, new SecureRandom());
            JavaHttpRequest.socketFactory = sc.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException | NoSuchProviderException e) {
            log.error("https信息证书注册失败!", e);
            throw new RuntimeException();
        }
    }

    public String readURLByHttpsGet(String url, String charset) throws Exception {
        String content = "";
        // 尝试连10次
        boolean suc = false;
        try {
//              URL net = new URL(url);//此法会抛异常
            URL net = new URL(url);//重要，必须要传入new Handler()，否则会抛异常
            InputStream in = null;
            HttpsURLConnection conn = (HttpsURLConnection) net.openConnection();//重要
            conn.setSSLSocketFactory(null);//重要
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            in = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
            StringBuffer sb = new StringBuffer();
            int ch;
            while ((ch = br.read()) != -1) {
                sb.append((char) ch);
            }
            in.close();
            content = sb.toString();
            suc = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!suc) {
            throw new Exception("读取 失败:" + url);
        }
        return content;
    }

    public static String sendPost(String uri, String charset, Map<String, Object> bodyMap, Map<String, String> headerMap) {
        String result = null;
        PrintWriter out = null;
        InputStream in = null;
        try {
            URL url = new URL(uri);
            HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
            urlcon.setDoInput(true);
            urlcon.setDoOutput(true);
            urlcon.setUseCaches(false);
            urlcon.setRequestMethod("POST");
            if (!headerMap.isEmpty()) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    urlcon.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            // 获取连接
            urlcon.connect();
            out = new PrintWriter(urlcon.getOutputStream());
            //请求体里的内容转成json用输出流发送到目标地址
//            out.print(JSON.toJSONString(bodyMap));
            out.flush();
            in = urlcon.getInputStream();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(in, charset));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("[请求异常][地址：" + uri + "][错误信息：" + e.getMessage() + "]");
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            } catch (Exception e2) {
                System.out.println("[关闭流异常][错误信息：" + e2.getMessage() + "]");
            }
        }
        return result;
    }


    public String exec(String uri, HttpMethod httpMethod, String charset, Map<String, String> headers, String params) {
        try {
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(httpMethod.name());
            if ("https".equals(url.getProtocol().toLowerCase())) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;
                httpsURLConnection.setHostnameVerifier((hostname, session) -> true);
                httpsURLConnection.setSSLSocketFactory(socketFactory);
            }
            // 设置请求头
            if (null != headers && !headers.isEmpty()) {
                headers.forEach(connection::setRequestProperty);
            }
            // 获取连接
            connection.connect();

            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.print(params);
            out.flush();

            InputStream in = connection.getInputStream();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(in, charset));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
            String result = sb.toString();


        } catch (IOException e) {

        }


        return null;
    }
}
